<?php

namespace App\Admin\Extensions;

use Encore\Admin\Grid;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Maatwebsite\Excel\Facades\Excel;

class CustomExporter extends AbstractExporter
{
    protected $filename = 'filename';
    protected $head = [];
    protected $fields = [];

    public function __construct(Grid $grid = null, $filename, $head, $fields)
    {
        parent::__construct($grid);
        $this->filename = $filename;
        $this->head = $head;
        $this->fields = $fields;
    }

    //导出备份 直接导出 但是只能导出grid->model() 获取的数据
    public function export()
    {
        Excel::create($this->filename, function($excel) {

            $excel->sheet('Sheetname', function($sheet) {

                // 从表格数据中取出需要导出的字段
                $head = $this->head;
                $fields = $this->fields;

                //init列
                $title_array = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH'];

                //写入标题
                $rows = collect([$head]);
                $sheet->rows($rows);

                // 从表格数据中取出需要导出的字段
                collect( $this->getData() )->map( function ($item, $k) use ($fields, $sheet, $title_array ) {
                    foreach ($fields as $i=>$keyName){
                        $v = array_get($item, $keyName);
                        $sheet->cell($title_array[$i] . ($k+2), function ($cell) use ($v) {
                            $cell->setValue($v);
                        });
                    }
                });

            });

        })->export('xls');
    }

}